package com.zhangzhibo.controller.user;

import com.zhangzhibo.pojo.User;
import com.zhangzhibo.service.user.UserService;
import com.zhangzhibo.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    //注册
    /*
       注册时不用设他的职位
       用户编码实时监测查重
       密码确认
     */
    @RequestMapping("/user/registerPage")
    public String registerPage(){
        return "register";
    }
    @RequestMapping("/user/register")
    public String register(HttpServletRequest request, HttpServletResponse response){
        User user = new User();
        try {
            user.setUserCode(request.getParameter("registerUserCode"));
            user.setUserName(request.getParameter("registerUserName"));
            user.setUserPassword(request.getParameter("ruserPassword"));
            user.setGender(Integer.parseInt(request.getParameter("gender")));
            user.setBirthday(DateUtils.StringToDate(request.getParameter("birthday"), DateUtils.shortDateFormat));//0000-00-00
            user.setPhone(request.getParameter("phone"));
            user.setAddress(request.getParameter("address"));
            System.out.println(user);
            userService.addUser(user);
            //response.getWriter().write("<script language='javascript'>alert('注册成功');</script>");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "redirect:/user/loginPage";
    }
    //用户修改，添加，注册时用户编码查重
    @RequestMapping("/user/register/checkUserCode")
    @ResponseBody
    public Boolean UserCodeCheckDuplicate(String registerUserCode, String OperationName, Integer id){
        User user = userService.getLoginInfo(registerUserCode,OperationName,id);
        return user==null;
    }


    //用户登录
    @RequestMapping("/user/loginPage")
    public String LoginPage(){
        return "login";
    }

    /**
     *
     * @param session 登录人员信息userSession存放在session中
     * @param username 表单参数用户名
     * @param password 表单参数密码
     * @param model 当用户不存在或密码错误时添加错误提示
     * @return
     */
    @RequestMapping("/user/login.do")
    public String LoginDo(HttpSession session, String username, String password, Model model){
        User user = userService.getLoginInfo(username,"",0);
        //判断
        if (user == null || !user.getUserPassword().equals(password)) {
            //查无此人
            //转发回登录页面 提示 用户名或密码错误
            model.addAttribute("error","*用户名或密码错误");
            return "login";
        }
        //查有此人
        //将用户的信息放在session中
        session.setAttribute("userSession",user);
        //跳转到主页
        return "redirect:/user/main";
    }
    //用户退出登录
    @RequestMapping("/user/logout.do")
    public String LogoutDo(HttpSession session){
        //移除session中userSession属性
        session.removeAttribute("userSession");
        return "redirect:/user/loginPage";
    }
    //主界面
    @RequestMapping("/user/main")
    public String mainPage(){
        return "main";
    }


    //用户管理界面
    @RequestMapping("/user/userDo/queryPage")
    public String UserDoQueryPage(Model model){
        return "userlist";
    }
    @RequestMapping("/user/userDo/query")
    @ResponseBody
    public Map<String,Object> UserDoQuery(Model model, String name, Integer userRole, int currentPageNo, int pageSize){
        Map<String,Object> map = QueryInformation(model, name, userRole, currentPageNo, pageSize);//记录查询信息
        return map;
    }
    //真正的查询代码
    public Map<String,Object> QueryInformation(Model model, String name, Integer userRole, int currentPageNo, int pageSize){
        Map<String,Object> map = new HashMap<>();
        List<User> userList = userService.getUserList(name, userRole, currentPageNo, pageSize);
        //根据查询条件的不同总数与总页数也不同
        int totalNum = userService.getUserCounts(name, userRole);
        int totalPage = (totalNum/pageSize);
        if(totalPage < (float) totalNum/pageSize){
            totalPage = totalPage+1;
        }
        map.put("userList",userList);
        map.put("totalNum",totalNum);
        map.put("totalPage",totalPage);
        return map;
    }



    //员工添加
    @RequestMapping("/user/userDo/addPage")
    public String UserDoAddPage(Model model){
        return "adduser";
    }
    @RequestMapping("/user/userDo/add")
    public String UserDoAdd(HttpServletRequest request,HttpServletResponse response){
        User user = new User();
        //前端传来的日期字符串格式为“yyyy-MM-dd”
        DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        try {
            user.setUserCode(request.getParameter("userCode"));
            user.setUserName(request.getParameter("userName"));
            user.setUserPassword(request.getParameter("ruserPassword"));
            user.setGender(Integer.parseInt(request.getParameter("gender")));
            user.setBirthday(date.parse(request.getParameter("birthday")));
            user.setPhone(request.getParameter("phone"));
            user.setAddress(request.getParameter("address"));
            user.setUserRole(Integer.parseInt(request.getParameter("userRole")));
            userService.addUser(user);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "redirect:/user/userDo/queryPage";
    }


    //员工信息查看
    @RequestMapping("/user/userDo/check")
    @ResponseBody
    public User checkUser(Integer id){
        User byId = userService.findById(id);
        return byId;
    }


    //信息修改
    @RequestMapping("/user/userDo/modifyPage")
    public String UserDoModifyPage(Model model,Integer id,HttpServletRequest request){
        User byId = userService.findById(id);
        String s = DateUtils.DateToString(byId.getBirthday(),DateUtils.timeDateFormat);
        model.addAttribute("user",byId);
        model.addAttribute("birthday",s);
        if(request.getParameter("Jump")!=null){
            model.addAttribute("Jump","main");
        }
        return "modifyuser";
    }
    @RequestMapping("/user/userDo/modify")
    public String UserDoModify(HttpServletRequest request,HttpServletResponse response){
        User user = new User();
        try {
            user.setId(Integer.parseInt(request.getParameter("id")));
            user.setUserCode(request.getParameter("userCode"));
            user.setUserName(request.getParameter("userName"));
            user.setUserPassword(request.getParameter("userPassword"));
            user.setGender(Integer.parseInt(request.getParameter("gender")));
            user.setBirthday(DateUtils.StringToDate(request.getParameter("birthday"),DateUtils.timeDateFormat));
            user.setPhone(request.getParameter("phone"));
            user.setAddress(request.getParameter("address"));
            /*
              个人信息修改界面没有职位的人员（userRole=0），普通员工3（userRole=3）职位栏不可修改，
              点击修改后，这个框里是没有值的，用request.getParameter("userRole")取值时，3会变为
              0。同时没有职位的人员与普通员工是进不了用户管理页面的，所以在这里做一下判断登录人员的职
              位为0或3时直接将值传入即可。
             */
            int role = ((User)request.getSession().getAttribute("userSession")).getUserRole();
            if(role == 0||role == 3){
                user.setUserRole(role);
            }else{
                user.setUserRole(Integer.parseInt(request.getParameter("userRole")));
            }
            userService.modify(user);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(request.getParameter("Jump").equals("main")){
            return "redirect:/user/main";
        }
        return "redirect:/user/userDo/queryPage";
    }


    //删除员工信息
    @RequestMapping("/user/userDo/delete")
    public String deleteUser(Integer id){
        userService.deleteUser(id);
        //System.out.println("经过了/user/userDo/delete");
        return "forward:/user/userDo/query";
    }

}
